<?php

/**
 * 客商资料管理
 */

namespace App\Http\Controllers;
use App\Models\Goods;
use App\Models\GoodsCat;
use App\Models\GoodsStock;
use App\Models\GoodsStockHis;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;


class GoodsController extends BaseController
{

    /**
     * Display a listing of the resource.
     *
     * @return JsonResponse|\Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $name = $request->get("goodsName");
        $goodsCat = $request->get("goodsCat");
        $pageNum = $request->get("page_num");
        $pageSize = $request->get("page_size", 10);
        $where = [['status', 1]];
        if ($goodsCat) {
            $where[] = ["cat_id", $goodsCat];
        }
        $goodsList = Goods::where($where)
            ->with(['goods_cat_info', 'goods_stock'])
            ->where(function ($query) use ($name) {
                return $query->when($name, function ($query) use ($name) {
                    $name = str_replace(" ", "", strtolower($name));
                    return $query->where('name', "like", "%" . $name . "%");
                });

            })
            ->orderBy("updated_at", "desc")
            ->paginate($pageSize, ['*'], "page", $pageNum);
        $list = $goodsList->getCollection();
        return Success(10100, [
            "data" => $list,
            "page_info" => [
                'current' => $goodsList->currentPage(), 'page_size' => (int)$pageSize, "count" => $goodsList->total(),
                "pages" => $goodsList->lastPage()
            ]
        ]);
    }


    public function goodsImage(Request $request)
    {
        if (!$request->hasFile("goodsImage")) {
            return Failed(10002, ["File" => "GoodsController", "line" => __LINE__, "need_filed" => ['goodsImage']]);
        }
        $allow = [
            'jpg',
            'jpeg',
            'png',
            'gif',
            'bmp',
            'JPG',
            'JPEG',
            'PNG',
            'GIF',
            'BMP'
        ];
        $file = $request->file('goodsImage');
        $originalName = $file->getClientOriginalName(); // 文件原名
        $ext = $file->getClientOriginalExtension();     // 扩展名
        $realPath = $file->getRealPath();   //临时文件的绝对路径


        $type = $file->getClientMimeType();     // image/jpeg
        $dir = '/image/goods/';

        if (!file_exists(public_path($dir))) {
            mkdir(public_path($dir), 0775, true);
            chmod(public_path($dir), 0775);
        }
        if (!in_array(strtolower($ext), $allow)) {
            return Failed(10002, ["File" => "GoodsController", "line" => __LINE__, "allow_ext" => $allow]);
        }

        $filename = time() . "." . strtolower($ext);
        try {
            $file->move(public_path($dir), $filename);
        } catch (\Exception $exception) {
            dd($exception->getCode());
        } catch (\Throwable $e) {
            dd($e->getCode(), $e->getMessage());
        }

        return $this->success(200, "文件上传成功", ['file_path' => $dir . $filename]);

    }

    /**
     * 商品新增
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function store(Request $request): JsonResponse
    {
        //
        $name = $request->get("name");
        $goods_image = $request->get("goods_image");
        $goods_cat = $request->get("goods_cat");
        $goods_desc = $request->get("goods_desc");
        if (!$name || !$goods_image || !$goods_cat || !$goods_desc) {
            return Failed(10002, ["file" => "GoodsController", "line" => __LINE__, "need_filed" => ['name', 'goods_image', 'goods_cat', 'goods_desc',]]);
        }
        $goods_cat_info = GoodsCat::where("id", $goods_cat)->first();
        if (!$goods_cat_info || $goods_cat_info->status != 1) {
            return $this->fail(10002, "商品类别不存在", ["file" => "GoodsController", "line" => __LINE__, "goods_cat_not_exits" => $goods_cat]);
        }
        $goods_info = Goods::where([['name', $name], ['cat_id', $goods_cat], ['status', 1]])->first();
        if ($goods_info) {
            return Failed(10001, ["file" => "GoodsController", "line" => __LINE__, "goods_exit" => $request->all()]);
        }
        $goods = new Goods();
        $goods->name = $name;
        $goods->cat_id = $goods_cat;
        $goods->image = $goods_image;
        $goods->goods_desc = $goods_desc;
        $goods->status = 1;
        $goods->updated_at = date("Y-m-d H:i:s");
        $goods->created_at = date("Y-m-d H:i:s");
        if (!$goods->save()) {
            return Failed(10001, ["file" => "GoodsController", "line" => __LINE__, "goods_store" => $goods]);
        }
        return Success(10000, []);
    }

    /**
     * 客商资料维护---公司编辑
     *
     * @param Request $request
     * @param int $id
     * @return JsonResponse
     */
    public function update(Request $request, int $id): JsonResponse
    {
        if (!$id) {
            return Failed(10002, ["file" => "GoodsController", "line" => __LINE__, "need_filed" => ['id']]);
        }
        $cat_id = $request->get("cat_id");
        $name = $request->get("name");
        $goods_desc = $request->get("goods_desc");
        $image = $request->get("image");
        $goods = Goods::where("id",$id)->first();
        if (!$goods || $goods->status != 1) {
            return Failed(10005, ["file" => "GoodsController", "line" => __LINE__, "resources" => "not_found"]);
        }
        $goods->name = $name;
        $goods->cat_id = $cat_id;
        $goods->image = $image;
        $goods->goods_desc = $goods_desc;
        $goods->updated_at = date("Y-m-d H:i:s");
        if (!$goods->save()) {
            return Failed(10001, ["file" => "GoodsController", "line" => __LINE__, "goods_store" => $goods]);
        }
        return Success(10000, []);
    }

    /**
     * 商品库存初始化
     * @param Request $request
     * @param int $id
     * @return JsonResponse
     */
    public function goodsStock(Request $request, int $id): JsonResponse
    {
        if (!$id) {
            return Failed(10002, ["file" => "GoodsController", "line" => __LINE__, "need_filed" => ['id']]);
        }
        $total_num = $request->get("total_num");
        $use_num = $request->get("use_num");
        $leave_num = $request->get("leave_num");
        $bad_num = $request->get("bad_num", 0);
        $warn_num = $request->get("warn_num");
        $day_per = $request->get("day_per");

        $user_id = $this->user->id;
        $goods_id = $id;

        if (($total_num - $use_num - $bad_num) < 0 || ($total_num - $use_num - $bad_num) != $leave_num) {
            return $this->fail(10002, "请检查总数、领用数、报损数", ["file" => "GoodsController", "line" => __LINE__, "need_check_filed" => ['total_num', 'use_num', 'bad_num']]);
        }

        $goods = Goods::where('id', $id)->first();
        if (!$goods || $goods->status != 1) {
            return Failed(10005, ["file" => "GoodsController", "line" => __LINE__, "resources" => "not_found"]);
        }

        $goods->day_per = $day_per;
        $goods->updated_at = date("Y-m-d H:i:s");

        // 修改商品每日限制
        if (!$goods->save()) {
            return $this->fail(10002, "修改商品每日限制失败", ["file" => "GoodsController", "line" => __LINE__]);
        }
        // 开启事务
        DB::beginTransaction();
        try{
            $goods_stock = GoodsStock::where('goods_id', $goods_id)->first();
            if (!$goods_stock) {
                // 商品实时库存表记录不存在 则初始化库存 并记录 商品库存历史
                $goods_stock = new GoodsStock();
                $goods_stock->goods_id = $goods_id;
                $goods_stock->total_num = $total_num;
                $goods_stock->use_num = $use_num;
                $goods_stock->bad_num = $bad_num;
                $goods_stock->leave_num = $total_num - $use_num - $bad_num;
                $goods_stock->warn_num = $warn_num;
                $goods_stock->updated_at = date("Y-m-d H:i:s");
                $goods_stock->created_at = date("Y-m-d H:i:s");
                if (!$goods_stock->save()) {
                    return $this->fail(10002, "初始化库存失败", ["file" => "GoodsController", "line" => __LINE__]);
                }
                $goods_stock_his = new GoodsStockHis();
                $goods_stock_his->goods_id = $goods_id;
                $goods_stock_his->user_id = $user_id;
                $goods_stock_his->date = date("Y-m-d H:i:s");
                $goods_stock_his->goods_action = '入库';
                $goods_stock_his->total_num =  $total_num;
                $goods_stock_his->stock_total_num += $total_num;
                $goods_stock_his->stock_use_num += $use_num;
                $goods_stock_his->stock_leave_num +=  $goods_stock->leave_num;
                $goods_stock_his->stock_bad_num += $bad_num;
                $goods_stock_his->updated_at = date("Y-m-d H:i:s");
                $goods_stock_his->created_at = date("Y-m-d H:i:s");
                if (!$goods_stock_his->save()) {
                    return $this->fail(10002, "记录商品库存历史记录失败", ["file" => "GoodsController", "line" => __LINE__]);
                }
            } else {
                // 商品实时库存表记录 存在 则只修改 warn_num(告警数量)
                $goods_stock->warn_num = $warn_num;
                $goods_stock->updated_at = date("Y-m-d H:i:s");
                if (!$goods_stock->save()) {
                    return $this->fail(10002, "编辑告警数量保存失败", ["file" => "GoodsController", "line" => __LINE__]);
                }
            }
        }catch (\Exception $exception){
            DB::rollBack();
            return $this->fail(10002,   "商品配置操作记录失败/".$exception->getMessage(), ["file" => "GoodsController=>".$exception->getFile(), "line" => __LINE__."/".$exception->getLine(),]);
        }

        DB::commit();
        return Success(11000, []);
    }

    public function goodsStockOperation(Request $request): JsonResponse
    {
        $goods_id = $request->get("goods_id");
        $total_num = $request->get("total_num");
        $goods_action = $request->get("goods_action");
        if (!$goods_id || !$total_num || !$goods_action) {
            return Failed(10005, ["file" => "GoodsController", "line" => __LINE__, "need_filed" => ['goods_id', 'total_num', 'goods_action']]);
        }

        $goods = Goods::where('id', $goods_id)->first();
        if (!$goods || $goods->status != 1) {
            return Failed(10005, ["file" => "GoodsController", "line" => __LINE__, "resources" => "goods_not_found"]);
        }

        $goods_stock = GoodsStock::where('goods_id', $goods_id)->first();

        if (!$goods_stock) {
            return Failed(10005, ["file" => "GoodsController", "line" => __LINE__, "resources" => "goods_stock_not_found"]);
        }

        if ($goods_action != "进货") {
            $temp_leave = $goods_stock->total_num - $goods_stock->use_num - $goods_stock->bad_num - $total_num;

            if ($temp_leave < 0 || $temp_leave > $goods_stock->leave_num) {
                return $this->fail(10002, $goods_action . "数量 [" . $total_num . "] 超过总计可用数量 [" . $goods_stock->leave_num . "]", ["file" => "GoodsController", "line" => __LINE__]);
            }
        }
        // 开启事务
        DB::beginTransaction();
        try{
            switch ($goods_action) {
                case "领用":
                     GoodsStock::goods_use($total_num, $goods_stock);
                    break;
                case "报损":
                     GoodsStock::goods_bad($total_num, $goods_stock);
                    break;
                case "进货":
                     GoodsStock::goods_add($total_num, $goods_stock);
                    break;
                default;
            }
                     GoodsStockHis::log($this->user->id, $goods_id, $goods_action, $total_num);
        }catch (\Exception $exception){
            DB::rollBack();
            return $this->fail(10002, $goods_action . "库存操作记录失败", ["file" => "GoodsController=>".$exception->getFile(), "line" => __LINE__."/".$exception->getLine(),]);
        }
        DB::commit();
        return Success(11000, []);
    }

    /**
     * 商品删除
     *
     * @param int $id
     * @return JsonResponse
     */
    public function destroy(int $id): JsonResponse
    {
        //
        if (!$id) {
            return Failed(10002, ["File" => "GoodsController", "line" => __LINE__, "need_filed" => ['id']]);
        }
        DB::beginTransaction();

        $goods = Goods::where([["id", $id],["status", 1]])->first();
        if (!$goods) {
            return Failed(10005, ["File" => "GoodsController", "line" => __LINE__, "resource" => "not_found"]);
        }
        try {
            $goods->status = 0;
            $goods->updated_at = date("Y-m-d H:i:s");
            if(!$goods->save()){
                return $this->fail(10002,  "删除失败", ["file" => "GoodsController=>", "line" => __LINE__,]);
            }
            //更改 库存历史记录表 goods_stock_his
            GoodsStockHis::where("goods_id",$goods->id)->update(
                [
                    "status"=>0,
                    "updated_at"=>date("Y-m-d H:i:s")
                ]
            );
        }catch (\Exception $exception){
            DB::rollBack();
            return $this->fail(10002,  "删除失败", ["file" => "GoodsController=>".$exception->getFile(), "line" => __LINE__."/".$exception->getLine(),]);
        }
        DB::commit();
        return Success(10700, ["File" => "GoodsController", "line" => __LINE__, "resource" => "delete_success"]);
    }

    /**
     * 客商资料维护--公司相关人员新增
     * @param Request $request
     * @param int $id
     * @return JsonResponse
     */
    public function useradd(Request $request, int $id): JsonResponse
    {
        if (!$id) {
            return Failed(10002, ["File" => "CompanyController", "line" => __LINE__, "need_filed" => ['id']]);
        }
        $company = Company::where([["id", $id], ['status', 1]])->first();
        if (!$company) {
            return Failed(10005, ["File" => "CompanyController", "line" => __LINE__, "resource" => "not_found"]);
        }
        $model = $request->get("model");
        $user_id = $request->get("user_id");
        if (!$model || !$user_id) {
            return Failed(10002, [
                "file" => "CompanyController", "line" => __LINE__,
                "need_filed" => ['model', 'user_id']
            ]);
        }
        if (!in_array($model, $this->allow_model)) {
            return Failed(10301, [
                "file" => "CompanyController", "line" => __LINE__,
                "allow_model_filed" => $this->allow_model
            ]);
        }
        $data = [
            "company_id" => $id,
            "user_id" => $user_id
        ];

        $res = $this->model[$model]::where([["company_id", $id]])->updateOrCreate($data);
        if (!$res) {
            return Failed(10002,
                ["File" => "CompanyController", "line" => __LINE__, "updated_error" => "添加相关人员失败"]);
        }
        return Success(11000,
            ["File" => "CompanyController", "line" => __LINE__, "updated_success" => "添加相关人员成功"]);
    }

    /**
     * 客商资料维护--公司相关人员删除
     * @param Request $request
     * @param int $id
     * @return JsonResponse
     */
    public function userdel(Request $request, int $id): JsonResponse
    {
        if (!$id) {
            return Failed(10002, ["File" => "CompanyController", "line" => __LINE__, "need_filed" => ['id']]);
        }
        $company = Company::where([["id", $id], ['status', 1]])->first();
        if (!$company) {
            return Failed(10005, ["File" => "CompanyController", "line" => __LINE__, "resource" => "not_found"]);
        }
        $model = $request->get("model");
        $user_id = $request->get("user_id");
        if (!$model || !$user_id) {
            return Failed(10002, [
                "file" => "CompanyController", "line" => __LINE__,
                "need_filed" => ['model', 'user_id']
            ]);
        }
        if (!in_array($model, $this->allow_model)) {
            return Failed(10301, [
                "file" => "CompanyController", "line" => __LINE__,
                "allow_model_filed" => $this->allow_model
            ]);
        }
        $res = $this->model[$model]::where([["company_id", $id], ['user_id', $user_id]])->delete();
        if (!$res) {
            return Failed(10007,
                ["File" => "CompanyController", "line" => __LINE__, "resources" => "delete_failed"]);
        }
        return Success(10700,
            ["File" => "CompanyController", "line" => __LINE__, "resources" => "delete_success"]);
    }

    /**
     * 客商资料维护--公司类别编辑
     * @param Request $request
     * @param int $id
     * @return JsonResponse
     */
    public function category(Request $request, int $id): JsonResponse
    {
        if (!$id) {
            return Failed(10002, ["File" => "CompanyController", "line" => __LINE__, "need_filed" => ['id']]);
        }
        $company = Company::where([["id", $id], ['status', 1]])->first();
        if (!$company) {
            return Failed(10005, ["File" => "CompanyController", "line" => __LINE__, "resource" => "not_found"]);
        }
        $categoryArr = $request->get("categoryArr");

        if (empty($categoryArr)) {
            return Failed(10002, [
                "file" => "CompanyController", "line" => __LINE__,
                "need_filed" => ['categoryArr']
            ]);
        }
        if (!empty(CompanyCategory::where([["company_id", $id]])->get()->toArray())) {
            $res = CompanyCategory::where([["company_id", $id]])->delete();
            if (!$res) {
                return Failed(10007,
                    ["File" => "CompanyController", "line" => __LINE__, "resources" => "delete_failed", "msg" => "公司类别删除失败"]);
            }
        }

        $data = [];
        foreach ($categoryArr as $vo) {
            $data[] = [
                "company_id" => $id,
                "category_id" => $vo
            ];
        }

        if (!CompanyCategory::insert($data)) {
            return Failed(10002,
                ["File" => "CompanyController", "line" => __LINE__, "updated_error" => "公司类别编辑失败"]);
        }
        return Success(11000,
            ["File" => "CompanyController", "line" => __LINE__, "updated_success" => "公司类别编辑成功"]);
    }

    /**
     * 保存 公司业务范围
     * @param array $business_arr
     * @param $company
     * @return true
     */
    public function BusinessScope(array $business_arr, $company): bool
    {
        foreach ($business_arr as $vo) {
            CompanyBusiness::create([
                "company_id" => $company->id,
                "business_id" => $vo
            ]);
        }
        return true;
    }

    public function getCompanyIdByUserId($user_id)
    {
        if (!$user_id) {
            return false;
        }

    }

}
